<template>
  <div class="wang-editor-wrapper">
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 300px; overflow-y: hidden"
        v-model="html"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onChange="onChange"
        @onCreated="onCreated"
      />
    </div>
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getToken } from '@/utils/auth'

export default {
  name: 'WangEditor',
  components: { Editor, Toolbar },
  props: {
    content: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      editor: null,
      html: '<p><br/></p>',
      toolbarConfig: {
        excludeKeys: ['fullScreen']
      },
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            maxFileSize: 20 * 1024 * 1024,
            server: 'https://api.zctj16888.com/admin/v1/image/ossUpload',
            fieldName: 'image',
            customInsert: (res, insertFn) => {
              if (res.data && res.data.url) {
                insertFn(res.data.url)
              }
            }
          },
          uploadVideo: {
            maxFileSize: 200 * 1024 * 1024,
            server: 'https://api.zctj16888.com/admin/v1/image/ossUpload',
            fieldName: 'image',
            customInsert: (res, insertFn) => {
              if (res.data && res.data.url) {
                insertFn(res.data.url)
              }
            }
          }
        }
      },
      mode: 'default'
    }
  },
  watch: {
    content: {
      handler(newVal) {
        if (newVal && newVal !== this.html) {
          this.html = newVal;
          console.log("WangEditor content updated:", newVal);
        }
      },
      immediate: true
    }
  },
  methods: {
    onChange(editor) {
      this.html = editor.getHtml();
      this.$emit('submit', this.html);
    },
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
      console.log("WangEditor created:", editor);
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (this.content) {
        this.html = this.content;
      }
      console.log("WangEditor mounted, content:", this.content);
    });
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy();
    }
  }
}
</script>

<style scoped>
.wang-editor-wrapper {
  width: 100%;
}

.wang-editor-wrapper :deep(.w-e-toolbar) {
  border-bottom: 1px solid #ccc;
}

.wang-editor-wrapper :deep(.w-e-text-container) {
  min-height: 300px;
}
</style>